<template>
	<wsPage :title="pageTitle+'优惠券'">
	    <Form ref="couponForm" :model="couponForm" :rules="validate" :label-width="100">
        	<FormItem label="优惠券名称" prop="name" class="ws-form-lable">
	            <Input v-model="couponForm.name" class="ws-form-select"></Input>
	        </FormItem>
	        <FormItem label="有效期类型" prop="expiredType" class="ws-form-lable">
	            <RadioGroup v-model="couponForm.expiredType">
	                <span><Radio label="1" >固定时间段</Radio></span>
	                <span><Radio label="2" >领取后多少天</Radio></span>
            	</RadioGroup>
	        </FormItem>
	        <FormItem label="有效期" v-show="couponForm.expiredType == 1">
	            <Row>
	                <Col span="4">
	                    <DatePicker type="date" placeholder="开始日期" v-model="couponForm.startDate"></DatePicker>
	                </Col>
	                <Col span="4">
	                    <DatePicker type="date" placeholder="截止日期" v-model="couponForm.endDate"></DatePicker>
	                </Col>
	            </Row>
	        </FormItem>
	        <FormItem v-if="couponForm.expiredType == 2" label="失效天数" prop="expiredDay" class="ws-form-lable" >
	            <Input v-model="couponForm.expiredDay" class="ws-form-select"></Input>
	        </FormItem>
	        <FormItem label="使用条件" prop="useCondition" class="ws-form-lable">
	            <RadioGroup v-model="couponForm.useCondition">
	                <span><Radio label="1" >无限制</Radio></span>
	                <span><Radio label="2" >满减</Radio></span>
            	</RadioGroup>
	        </FormItem>
	        <FormItem label="优惠金额" prop="couponAmount" class="ws-form-lable">
	            <Input v-model="couponForm.couponAmount" class="ws-form-select"></Input>
	        </FormItem>
	        <FormItem v-if="couponForm.useCondition == 2" label="满足金额" prop="satisfyAmount" class="ws-form-lable">
	            <Input v-model="couponForm.satisfyAmount" class="ws-form-select"></Input>
	        </FormItem>
	        <FormItem label="数量" prop="quantity" class="ws-form-lable">
	            <Input v-model="couponForm.quantity" class="ws-form-select" placeholder="不输入则视为不限制数量"></Input>
	        </FormItem>
	        <FormItem label="使用范围" prop="userange" class="ws-form-lable">
	            <RadioGroup v-model="couponForm.userange">
	                <span @click="chooseMerchant()"><Radio label="1" >店铺通用</Radio></span>
	                <span @click="queryCategory()"><Radio label="2" >商品基础类目</Radio></span>
	                <span @click="queryProduct()"> <Radio label="3" >商品</Radio></span>
            	</RadioGroup>
	        </FormItem>
	        <!--设置使用范围模态框-->
			<template v-if="this.couponForm.userange=='2'">
				<FormItem label="优惠模式" prop="categoryName" class="ws-form-lable" >
		            <Select clearable v-model="selectCategory" style="width:200px">
				        <Option v-for="item in categoryList" :label="item.categoryName" :key="item.categoryId" :value="item.categoryId"></Option>
				    </Select>
		            <Button type="info" @click="saveCategory">添加</Button>
		        </FormItem>
		        <Row>
		        	<Col :span="10" :offset="1">
						<Table border :columns="table.columns" :data="categoryList1"></Table>
					</Col>
		        </Row>
			</template>
			<!-- 商品模态框 -->
			<wsSmPanel  style="width: 40%;margin-left: 3%;"  v-if="this.couponForm.userange=='3'"> 
				<div slot="list_data" >
					<Table border 
						:columns="productTable.productColumns" 
						:data="productTable.productData">
					</Table>
				</div>
				<div slot="list_operate">
					<Button type="ghost" @click="addProduct" >添加商品</Button>
				</div>
			</wsSmPanel>
			<div class="edit-button-self">
				<Button type="primary" @click="couponOk">保存</Button>
				<Button @click="couponCancel">取消</Button>
			</div>
		</Form>	

		<!--添加商品弹框-->
		<wsModal v-model="addProductModal.detail" title="添加商品" @on-ok="saveAddProductModalDetail"  @on-cancel="cancelAddProductModalDetail" :width="800">
			<wsSmPanel  @simple-query="queryProductsList">
			<div slot="query_form">
				<Form :model="queryForm" :label-width="100" inline>
					<!-- <FormItem label="店铺名称" required class="ws-form-lable">
			            <Input v-model="queryForm.merchantName" class="ws-form-select"></Input>
			        </FormItem> -->
			        <FormItem label="商品类别" required class="ws-form-lable">
		            	<Select clearable v-model="queryForm.categoryId" class="ws-form-select">
					        <Option v-for="item in categoryList" :label="item.categoryName" :key="item.categoryId" :value="item.categoryId"></Option>
					    </Select>
			        </FormItem>
			        <FormItem label="商品名称" required class="ws-form-lable">
			            <Input v-model="queryForm.productName" class="ws-form-select"></Input>
			        </FormItem>
	        	</Form>
			</div>
    		<div slot="list_data" >
				<Table border :columns="productListTable.productColumns" :data="productListTable.productData" @on-selection-change="tableSelected"></Table>
			</div>
		</wsSmPanel>
		</wsModal>

	</wsPage>
</template>

<script>	
	import Util from '../../../common/util.js'
	import Common from '../../../common/common.js';
	export default {
		data() {
			return {
				selectCategory:null,//选中的分类
				userange:null,
				pageTitle:'新增',
				merchantName:'',
				productName:'',
                /**
                *优惠券表单
                */
				couponForm: {
					id:null,
					name: '',
					startDate:null,
					endDate:null,
					couponAmount:null,
					satisfyAmount:null,
					quantity:null,
					userange:null,
					useCondition:null,
					couponCategoryIds:[],
					couponProductIds:[],
					expiredDay:null,
					expiredType:null
				},
				//商品类型表
				table: {
					columns: [
					
					{
						title: '商品类型id',
                        key: 'categoryId',
                        align: 'center'
					},
					{
						title: '商品类型名称',
                        key: 'categoryName',
                        align: 'center'
					},
					{
						title: '操作',
						width: 120,
						fixed: 'right',
						align: 'center',
						render: (h, params) => {
							return h('div', [h('Button', {
								props: {
                                    type: 'text',
                                    size: 'small'
                                },
								on: {
									click: () => {
										this.handleRemoveBaseImage(params.row._index);
									}
								}
							}, '删除')])
						}
					}],
					categoryList1: [],
				},
				validate:{
					name: [
						{ required: true, message: '请输入名称', trigger: 'blur' }
					],
					useCondition: [
						{ required: true, message: '请选择使用条件', trigger: 'blur' }
					],
					userange: [
						{ required: true, message: '请选择使用范围', trigger: 'blur' }
					],
					expiredType: [
						{ required: true, message: '请选择有效期类型', trigger: 'blur' }
					],
					expiredDay: [
						{ required: true, message: '请输入失效天数'},
						{ validator:Common.validatePositiveInteger,trigger:'blur'}
					],
					couponAmount: [
						{ required: true, message: '请输入面值'},
						{ validator:Common.validatePositiveInteger,trigger:'blur'}
					],
					satisfyAmount: [
						{ required: true, message: '请输入满足金额'},
						{ validator:Common.validatePositiveInteger,trigger:'blur'}
					],
					quantity: [
						{ validator:Common.validatePositiveInteger,trigger:'blur'}
					],

				},
				queryForm:{
					merchantName : null,
					categoryName : null,
					categoryId : null,
					productName : null
				},	
				//参与优惠商品分类
				CouponProductCategoryDO:{
					couponId:null,
					categoryId:null,
					categoryName:null
				},
				//设置使用范围模态框
				couponRangeModal:{
					show:false
				},
				//新增基地地址设置
				addProductModal: {
					detail: false,
					form: {
						productName:'',
						name:''
					},
				},
				//商品列表
				productsList:[],
				categoryList:[],
				//基础类目弹框数据
				categoryList1:[],
				productsList2:[],
				//参与优惠商品
				CouponProductDO:{
					couponId:null,
					productId:null
				},
				//商品列表数据
				productTable: {
					productColumns: [
					{
                        title: '商品id',
                        key: 'productId',
                        align: 'center'
                    },{
						title: '商品名称',
                        key: 'productName',
                        align: 'center'
					},{
						title: '操作',
						width: 180,
						fixed: 'right',
						align: 'center',
						render: (h, params) => {
							return h('div', [h('Button', {
								props: {
                                    type: 'text',
                                    size: 'small'
                                },
								on: {
									click: () => {
										this.deleteProcut(params.row._index);
									}
								}
							}, '删除')])
						}
					}],
					productData: [],
					productData2:[]
				},
				//商品列表数据
				productListTable: {
					productColumns: [
					{			
						type: 'selection',
                        align: 'center',
                        width:80
					},
					{
                        title: '商品id',
                        key: 'productId',
                        align: 'center'
                    },{
						title: '商品名称',
                        key: 'productName',
                        align: 'center'
					}],
					productData: []
				}
				
			}
		},
		//注册局部组件
		computed: {
		},
		mounted() {
			this.init();
			this.queryCategoryList();
		},
		methods: {
			init() {
				if(this.$route.query.id != null && this.$route.query.id != '') {
					this.pageTitle='编辑';
					this.couponId = this.$route.query.id;
					this.queryById(this.couponId);
				} else {
					this.pageTitle='新增';
					this.editClear();
				}
			},
			// tableSelected2(selection_){
			// 	this.couponForm.couponCategoryIds = [];
			// 	for(i in selection_){
			// 		this.couponForm.couponCategoryIds.push(selection_[i].id);
			// 	}
			// 	console.log(this.couponForm.couponCategoryIds);
			// },
			// tableSelected3(selection_){
			// 	this.couponForm.couponProductIds = [];
			// 	for(i in selection_){
			// 		this.couponForm.couponProductIds.push(selection_[i].id);
			// 	}
			// },
			//条件查询商品
			queryProductsList(){
				let _this = this;
				_this.axios.post('/ws/ms/queryProductsList', _this.queryForm).then(function(response) {
						let res = response.data;	
						if(0 === res.meta.code) {
							// _this.productsList = res.data;
							_this.productListTable.productData = res.data;
						}else{
							let message_ = res.meta.message;
							_this.$Message.warning(res.meta.message);
						}
					});
			},
			//查询商铺下面的所有商品分类
			queryCategoryList(){
				const _this = this;
				_this.axios.get('/ws/ms/couponProductCategorys/tenantId').then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if (0 == resMeta.code) {
						_this.categoryList = res.data;
					} else {
						_this.$Message.warning(resMeta.message);
					}
				});
			},
			saveCategory(){
				// selectCategory
				const _this = this;
				let whetherRepeat = false;
				this.categoryList1.forEach(function (value) {
					if(_this.selectCategory == value.categoryId){
						whetherRepeat = true;
						// _this.$Message.warning("已经存在该分类！");
						return;
					}
				});
				if (whetherRepeat) {
					_this.$Message.warning("已经存在该分类！");
					return;
				}
				this.categoryList.forEach(function (value) {
					if (_this.selectCategory == value.categoryId) {
						_this.categoryList1.push(value);
						return;
					}
				});
			},
			/**
			 * 选择
			 */
			tableSelected(selection_){
				// this.table.selection = selection_;
				this.productsList2 = [];
				for(i in selection_){
					this.productsList2.push(selection_[i]);
				}
			},
			 /**
			 *  商品分类确认按钮
			 */
			saveAddProductModalDetail(){
				if(this.productTable.productData.length == 0){
					this.productTable.productData = this.productsList2;
				}
				else{
					//循环遍历模态框中的集合
					for(var i = 0;i<this.productsList2.length;i++){
						var n = 0;
						//遍历原集合
						for(var j = 0;j<this.productTable.productData.length;j++){
							//如果有相等情况，说明此商品已经有了
							if(this.productTable.productData[j].productId == this.productsList2[i].productId){
								n++;
							}
						}
						//给元数组里面添加新的商品
						if(n == 0){
							this.productTable.productData.push(this.productsList2[i]);
						}
					}
				}
				this.productListTable.productData= [];
				this.queryForm.categoryId = '';
				this.addProductModal.detail = false;
			},
			/**
			 * 商品分类取消
			 */
			cancelAddProductModalDetail(rowId){
				this.productListTable.productData= [];
				this.queryForm.categoryId = '';
				this.addProductModal.detail = false;
			},
			addProduct(){
				this.addProductModal.detail = true;
			},

			//修改使用范围时，需更改表中的数据，只能选择一种类型
			chooseMerchant(){
				this.couponForm.couponCategoryIds = [];
				this.couponForm.couponProductIds = [];
			},
			// //打开设置使用范围模态框
			// settingUseRange(rowId,userange){
			// 	this.couponId=rowId;
			// 	this.userange=userange;
			// 	if(userange==2){
			// 		this.queryCategoryList();
			// 	}
			// 	if(userange==3){
			// 		this.queryProductList();
			// 	}
			// 	this.couponRangeModal.show=true;
			// },
			//关闭设置使用范围模态框
			couponRangeModalCancel(){
				this.couponRangeModal.show=false;
				this.couponForm.couponCategoryIds = [];
				this.couponForm.couponProductIds = [];
				// this.init();
			},
			couponRangeModalOK(){
				this.couponRangeModal.show=false;
				// this.init();
			},
			/**
			 * 商品分类删除
			 */
			handleRemoveBaseImage(index){ 
        	     // 删一个数组元素 
        		 this.categoryList1.splice(index,1);    	 	
        	},
        	deleteProcut(index){
        		// 删一个数组元素
        		this.productTable.productData.splice(index,1);  
        	},
			/**
			*选择基础类目
			*/
			queryCategory(){
				this.couponForm.couponCategoryIds = [];
				this.couponForm.couponProductIds = [];
			},
			//查询基础类目列表
			// queryCategoryList(){
				// this.range=2;
				// let pageSize = this.categoryTable.categoryPage.pageSize;
				// let pageNum = this.categoryTable.categoryPage.pageNum;
				// this.CouponProductCategoryDO.couponId=this.couponId;
				// let postData_ = this.CouponProductCategoryDO;
				// const _this = this;
				// this.axios.post('/ws/ms/couponProductCategorys/findByProduct?pageNum=' + pageNum + '&pageSize=' + pageSize,postData_).then(response => {
				// 	var res = response.data;
				// 	var resMeta = res.meta;
				// 	if (0 == resMeta.code) {
				// 		_this.buildCategoryPageData(res.data);
				// 		_this.couponRangeModal.show = true;
				// 	} else {
				// 		_this.$Message.warning(resMeta.message);
				// 	}
				// });
			// },
			//构建基础类目表格数据
			buildCategoryPageData(data_) {
				this.categoryTable.categoryData = data_.list;
				this.categoryTable.categoryPage.total = data_.total;
			},
			//选择基础类目操作
			chooseCategory(rowId,categoryCoupon){
				if(categoryCoupon==1){
					//取消选择
					this.unChooseCategory(rowId);
				}else{
					const _this = this;
					_this.CouponProductCategoryDO.couponId=_this.couponId;
					_this.CouponProductCategoryDO.categoryId=rowId;
					let postData_ = _this.CouponProductCategoryDO;
					_this.axios.post('/ws/ms/couponProductCategory', postData_).then(function(response) {
						let res = response.data;				
						if(0 === res.meta.code) {
							_this.$Message.success(res.meta.message);
							_this.queryCategoryList();
						}else{
							let message_ = res.meta.message;
							_this.$Message.warning('选择失败:' + message_);
						}
					});
				}
			},
			//取消选择基础类目
			unChooseCategory(rowId){
				const _this = this;
				this.axios.delete('/ws/ms/deleteCouponProductCategory/' + rowId + '/couponId/' + this.couponId ).then(function(response) {
		      		let res = response.data;
					if(0 === res.meta.code) {
						_this.$Message.success(res.meta.message);
						_this.queryCategoryList();
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('取消选择失败:' + message_);
					}	
			    });
			},

			queryCategorySelected(){
				const _this = this;
				this.axios.get('/ws/ms/couponProductCategorysSelected/' + _this.couponForm.id).then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if (0 == resMeta.code) {
						_this.categoryList1 = res.data;
					} else {
						_this.$Message.warning(resMeta.message);
					}
				});
			},
			queryProductSelected(){
				const _this = this;
				this.axios.get('/ws/ms/couponProductSelected/' + _this.couponForm.id).then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if (0 == resMeta.code) {
						_this.productTable.productData = res.data;
					} else {
						_this.$Message.warning(resMeta.message);
					}
				});
			},


			/**
			 * 选择商品
			 */
			queryProduct(){
				this.couponForm.couponCategoryIds = [];
				this.couponForm.couponProductIds = [];
			},
			// queryProductList(){
			// 	let pageSize = this.productTable.productPage.pageSize;
			// 	let pageNum = this.productTable.productPage.pageNum;
			// 	this.CouponProductDO.couponId=this.couponId;
			// 	let postData_ = this.CouponProductDO;
			// 	const _this = this;
			// 	this.axios.post('/ws/ms/couponProducts?pageNum=' + pageNum + '&pageSize=' + pageSize,postData_).then(response => {
			// 		var res = response.data;
			// 		var resMeta = res.meta;
			// 		if (0 == resMeta.code) {
			// 			_this.buildProductPageData(res.data);
			// 			_this.couponRangeModal.show = true;
			// 		} else {
			// 			_this.$Message.warning(resMeta.message);
			// 		}
			// 	});
			// },
			//构建商品表格数据
			// buildProductPageData(data_) {
			// 	this.productTable.productData = data_.list;
			// 	this.productTable.productPage.total = data_.total;
			// },
			//选择商品操作
			chooseProduct(rowId,couponProduct){
				if(couponProduct==1){
					//取消选择
					this.unChooseProduct(rowId);
				}else{
					const _this = this;
					_this.CouponProductDO.couponId=_this.couponId;
					_this.CouponProductDO.productId=rowId;
					let postData_ = _this.CouponProductDO;
					_this.axios.post('/ws/ms/couponProduct', postData_).then(function(response) {
						let res = response.data;				
						if(0 === res.meta.code) {
							_this.$Message.success(res.meta.message);
							_this.queryProductList();
						}else{
							let message_ = res.meta.message;
							_this.$Message.warning('选择失败:' + message_);
						}
					});
				}
			},
			//取消选择商品
			unChooseProduct(rowId){
				const _this = this;
				this.axios.delete('/ws/ms/deleteCouponProduct/' + rowId + '/couponId/' + this.couponId ).then(function(response) {
		      		let res = response.data;
					if(0 === res.meta.code) {
						_this.$Message.success(res.meta.message);
						_this.queryProductList();
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('取消选择失败:' + message_);
					}	
			    });
			},
			/**
			 * 重置表单
			 */
			editClear(){
				this.couponForm.id= null;
				this.couponForm.name= null;
				this.couponForm.startDate= null;
				this.couponForm.endDate= null;
				this.couponForm.couponAmount= null;
				this.couponForm.satisfyAmount= null;
				this.couponForm.quantity= null;
				this.couponForm.userange= null
			},
			/**
			 * 保存操作
			 */
			couponOk() {
				const _this = this;
				//使用条件 无限制和满减互斥
				//如果使用条件为无限制，则满足金额置为null
				if(_this.couponForm.useCondition == 1){
					_this.couponForm.satisfyAmount = null;
				}
				this.$refs['couponForm'].validate((valid) => {
					if (valid) {		
						//验证开始时间和结束时间
						var d = new Date();
						var currentDate = new Date(d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate());
						if((null != _this.couponForm.startDate && "" != _this.couponForm.startDate )&&(null != _this.couponForm.endDate && "" != _this.couponForm.endDate)){
							if(_this.couponForm.startDate>_this.couponForm.endDate){
								return _this.$Message.error('开始日期不能晚于结束日期');
							}
							if(_this.couponForm.endDate<currentDate){
								return _this.$Message.error('结束日期不能早于当前日期');
							}
						}
						if(_this.couponForm.expiredType == 1){
							if(null == _this.couponForm.startDate || "" == _this.couponForm.startDate ){
								return _this.$Message.error('请选择开始日期');
							}
							if(null == _this.couponForm.endDate || "" == _this.couponForm.endDate){
								return _this.$Message.error('请选择结束日期');
							}
						}
						if(_this.couponForm.useCondition == 2){
							if(Number(_this.couponForm.satisfyAmount) < Number(_this.couponForm.couponAmount)){
								return _this.$Message.error('优惠金额不能大于满足金额');
							}
						}
						if(_this.couponId) {
							_this.editDataDict();
						} else {
							_this.saveDataDict();
						}                    
                    } else {
                        _this.$Message.error('数据填写不完整，请完善您的数据');
                    }
                    
               });
			},
			/**
			 * 新增
			 */
			saveDataDict() {
				const _this = this;
				let useRange = _this.couponForm.userange;
				if(useRange == 2){
					this.categoryList1.forEach(function (value) {
						_this.couponForm.couponCategoryIds.push(value.categoryId);
					});
				}
				if(useRange == 3){
					this.productTable.productData.forEach(function (value) {
						_this.couponForm.couponProductIds.push(value.productId);
					});
				}
				let postData_ = _this.couponForm;
				_this.axios.post('/ws/ms/coupon', postData_).then(function(response) {
					let res = response.data;				
					if(0 === res.meta.code) {
						_this.$Message.success(res.meta.message);
						_this.couponCancel();
					}else{
						let message_ = res.meta.message;
						_this.$Message.warning('新增优惠券失败:' + message_);
					}
				});
			},
			/**
			 * 获取编辑时数据
			 */
			queryById(couponId){
				const _this = this;
				this.axios.get('/ws/ms/coupons/'+couponId).then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if (0 == resMeta.code) {
						_this.couponForm = res.data;
						_this.couponForm.userange = _this.couponForm.userange+'';
						_this.couponForm.useCondition = _this.couponForm.useCondition+'';
						_this.couponForm.expiredType = _this.couponForm.expiredType+'';
						if(_this.couponForm.quantity == -1){
							_this.couponForm.quantity = '';
						}
						if(_this.couponForm.userange == '2'){
							_this.queryCategorySelected();
						} else if(_this.couponForm.userange == '3'){
							_this.queryProductSelected();
						}	
					} else {
						_this.$Message.warning(resMeta.message);
					}
				});
			},
			/**
			 * 编辑
			 */
			editDataDict() {
				const _this = this;
				let postData_ = _this.couponForm;
				let userange = _this.couponForm.userange;
				if(2 == userange){
					_this.couponForm.couponCategoryIds = [];
					this.categoryList1.forEach(function (value) {
						_this.couponForm.couponCategoryIds.push(value.categoryId);
					});
				}
				if(3 == userange){
					_this.couponForm.couponProductIds = [];
					this.productTable.productData.forEach(function (value) {
						_this.couponForm.couponProductIds.push(value.productId);
					});
				}
				_this.axios.put('/ws/ms/coupons', postData_).then(function(response) {
					let res = response.data;				
					if(0 === res.meta.code) {
						_this.$Message.success(res.meta.message);
						_this.couponCancel();
					}else{
						let message_ = res.meta.message;
						_this.$Message.warning('修改优惠券失败:' + message_);
					}
				});
			},
			/**
			 * 取消操作
			 */
			couponCancel() {
				this.$router.push({name:'ms_coupon_list'});
			},
    		/**
             * 返回
             */
            goBack() {
    			this.$router.push({name:'ms_coupon_list'});
    		},

		}
	}
</script>

<style scoped>
	.ws-form-select {
		width: 80%;
	}
	.edit-button-self{
		margin: 20px;
	}
	.ws-form-lable {
		width: 80%;
	}
</style>